/**
 * MongoDB数据库文件读取流对象
 * Copyright(C) 2018 liumurong
 */

import { SliceReadStream } from "./slicereadstream";

import { MongoReceiver } from './mongoreceiver';
import { Collection, MongoClient, Db } from 'mongodb';
import { ReceiverHelper } from './receiverhelper';

/**
 * Mongodb....
 */
export class MongoReadStream extends SliceReadStream {

    /**
     * 
     * @param hash 文件MD5
     * @param connstr 链接字符串
     */
    constructor(hash: string, connstr: string, private _mongoBase: MongoReceiver) {
        super(hash, connstr);
    }

    /**
     * 读取文件
     */
    async _read() {
        const filter = { hash: this.hash };
        if (!this.metadata) {
            this.metadata = await this._mongoBase.getMetadata(this.hash);
        }
        if (!this.metadata || this.sliceIndex === this.metadata.slicecount) {
            this.push(null);
            return;
        }
        let chunk = await this._mongoBase.col.findOne({ ...filter, ...{ index: this.sliceIndex } });
        if (!chunk || !chunk.data) {
            // 读取到一片为空的数据，那么认为数据已经结束了
            this.push(null);
            return;
        }
        this.sliceIndex++;
        this.push(chunk.data.buffer);
    }
    /**
     * 销毁数据库链接
     */
    async _destroy() {
        await this._mongoBase.db.close();
    }
}

